package com.tianlang.jfinal.base;

import java.math.BigDecimal;
import java.util.Map;
import java.util.UUID;

import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Table;
import com.jfinal.plugin.activerecord.TableMapping;

/**
 * Model 优化修改
 * 
 * @author mcp
 *
 * @param <M>
 */
public class BaseModel<M extends Model<M>> extends Model<M> {

	protected static final long serialVersionUID = 1L;

	protected static final Log log = Log.getLog(BaseModel.class);

	public Table getTable() {
		return TableMapping.me().getTable(getClass());
	}

	@Override
	public Integer getInt(String attr) {
		Object obj = get(attr);
		if (obj == null) {
			return null;
		} else if (obj instanceof Integer) {
			return (Integer) obj;
		} else if (obj instanceof BigDecimal) {
			return ((BigDecimal) obj).intValue();
		} else if (obj instanceof String) {
			try {
				return Integer.parseInt((String) obj);
			} catch (Exception e) {
				throw new RuntimeException("String can not cast to Integer : " + attr.toString());
			}
		} else {
			try {
				return Integer.parseInt(obj.toString());
			} catch (Exception e) {
				throw new RuntimeException("Object can not cast to Integer : " + attr.toString());
			}
		}
	}

	/**
	 * 获取主键名称
	 * 
	 * @return
	 */

	public String getPKValue() {
		String[] pkNameArr = getTable().getPrimaryKey();
		if (pkNameArr.length == 1) {
			return this.getStr(pkNameArr[0]);
		} else {
			String pk = "";
			for (String pkName : pkNameArr) {
				pk += this.get(pkName) + ",";
			}
			return pk;
		}
	}

	/**
	 * 重写save方法
	 */
	@Override
	public boolean save() {
		String[] pkArr = getTable().getPrimaryKey();
		for (String pk : pkArr) {
			// 设置主键值
			this.set(pk, UUID.randomUUID().toString().replaceAll("-", ""));
		}
		return super.save();
	}

	public Map<String, Object> getAttrs() {
		return super._getAttrs();
	}

	public Object[] getAttrValues() {
		return super._getAttrValues();
	}

}
